class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(){}
    TreeNode(int val){
        this.val=val;
    }
    TreeNode(int val,TreeNode left,TreeNode right){
        this.val=val;
        this.left=left;
        this.right=right;
    }

}


public class Demo01 {
//    1.从中序与后序遍历序列构造二叉树
//    给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， postorder 是同一棵树的后序遍历，请你构造并返回这颗 二叉树 。
//    示例 1:
//    输入：inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
//    输出：[3,9,20,null,null,15,7]
//    示例 2:
//    输入：inorder = [-1], postorder = [-1]
//    输出：[-1]
//
//    public int i=0;
//    public TreeNode buildTree1(int[] preorder,int[] inorder){
//        return buildTreeChild1(preorder,inorder,0,inorder.length-1);
//    }
//    public TreeNode buildTreeChild1(int[] preorder,int[] inorder,int inbegin,int inend){
//        if(inbegin>inend){
//            return null;
//        }
//        TreeNode root=new TreeNode(preorder[i]);
//        int rootIndex=findIndex1(inorder,inbegin,inend,preorder[i]);
//        i++;
//        root.left=buildTreeChild1(preorder,inorder,inbegin,rootIndex-1);
//        root.right=buildTreeChild1(preorder,inorder,rootIndex+1,inend);
//        return root;
//    }
//    public int findIndex1(int[] inorder,int inbegin,int inend,int key){
//        for (int i = inbegin; i <= inend; i++) {
//            if(inorder[i]==key){
//                return i;
//            }
//        }
//        return -1;
//    }





//    2.从中序与后序遍历序列构造二叉树
//    示例 1:
//    输入：inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
//    输出：[3,9,20,null,null,15,7]
//    示例 2:
//    输入：inorder = [-1], postorder = [-1]
//    输出：[-1]
//
    public int i = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        i = postorder.length-1;
        return buildTreeChild(postorder,inorder,0,inorder.length-1);
    }
    public TreeNode buildTreeChild(int[] postorder, int[] inorder,int inbegin,int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[i]);
        int rootIndex = findIndex(inorder,inbegin,inend,postorder[i]);
        i--;
        root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);
        return root;
    }
    public int findIndex( int[] inorder,int inbegin,int inend, int key) {
        for(int i = inbegin;i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }


}













